﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using FrameDisplay.Services;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Collections.Specialized;
using System.Web;
using System.IO;

namespace FrameDisplayClient
{
    public partial class FrameDisplayClientForm : Form
    {
        private string serverUrl;
        private string accessCode;


        public FrameDisplayClientForm()
        {
            InitializeComponent();

            this.serverUrl = Settings.Default.ServerUrl;
            this.accessCode = Settings.Default.AccessCode;

            this.panelDropBox.DragEnter += new DragEventHandler(panelDropBox_DragEnter);
            this.panelDropBox.DragDrop += new DragEventHandler(panelDropBox_DragDrop);

            this.UpdateServerLabel();
        }
         

        private void UpdateServerLabel()
        {
            if (!String.IsNullOrEmpty(this.serverUrl))
            {
                this.linkLabelServerAddress.Text = this.serverUrl;
            }
            else
            {
                this.linkLabelServerAddress.Text = "edit";
            }

            if (!String.IsNullOrEmpty(this.accessCode))
            {
                this.linkLabelAccessCode.Text = this.accessCode;
            }
            else
            {
                this.linkLabelAccessCode.Text = "edit";
            }
        } 

        private IFrameDisplayService GetFrameDisplayService()
        {
            WebHttpBinding webHttpBinding = new WebHttpBinding();
            ChannelFactory<IFrameDisplayService> clientChannelFactory = new ChannelFactory<IFrameDisplayService>(
                webHttpBinding, new EndpointAddress(this.GetServiceUrl("FrameDisplayService")));
            clientChannelFactory.Endpoint.Behaviors.Add(new WebHttpBehavior());

            IFrameDisplayService clientChannel = clientChannelFactory.CreateChannel();
            return clientChannel;
        }


        void panelDropBox_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Text))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }      

        void panelDropBox_DragDrop(object sender, DragEventArgs e)
        {                     
            IFrameDisplayService clientChannel = this.GetFrameDisplayService();


            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                foreach (string file in files)
                {
                    string ext = Path.GetExtension(file).ToLowerInvariant();
                    if (ext == ".jpeg" || ext == ".jpg" || ext == ".png" || ext == ".bmp" || ext == ".gif")
                    {
                        FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
                        clientChannel.ShowImageFile(fs, this.accessCode);
                        return;
                    }
                }
            }

            if (e.Data.GetDataPresent(DataFormats.Text))
            {
                string text = e.Data.GetData(DataFormats.Text).ToString();
               
                Uri uri;
                try
                {
                    uri = new Uri(text);
                }
                catch (Exception ex)
                {
                    // TODO: Show errors in another way.
                    MessageBox.Show("Not a valid URL.");
                    return;
                }

                bool isYouTubeVideo = false;
                if (uri.Host == "youtube.com" || uri.Host == "www.youtube.com")
                {
                    // Get video id.
                    string query = uri.Query;
                    NameValueCollection queryValues = HttpUtility.ParseQueryString(query);
                    string videoID = queryValues["v"];
                    if (!String.IsNullOrEmpty(videoID))
                    {
                        isYouTubeVideo = true;
                        clientChannel.ShowYouTube(this.accessCode, videoID);
                    }
                }

                if (!isYouTubeVideo)
                {
                    clientChannel.ShowUrl(this.accessCode, text);
                }
            }
        }

        private void linkLabelServerAddress_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            FrameDisplayClient.UI.Settings.GetServerAddressForm getServerAddressForm = new FrameDisplayClient.UI.Settings.GetServerAddressForm();
            getServerAddressForm.ServerUrl = this.serverUrl;
            if (getServerAddressForm.ShowDialog(this) == DialogResult.OK)
            {
                this.serverUrl = getServerAddressForm.ServerUrl;

                // Save the change to settings.
                Settings.Default.ServerUrl = this.serverUrl;
                Settings.Default.Save();

                this.UpdateServerLabel();
            }
        }

        private string GetServiceUrl(string relativeServiceUrl)
        {
            string url = this.serverUrl;
            if (url.EndsWith("/"))
            {
                return url + relativeServiceUrl;
            }
            else
            {
                return url + "/" + relativeServiceUrl;
            }
        }

        private void buttonCheckConnection_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(this.serverUrl))
            {
                MessageBox.Show("Server URL not configured.", "Error");
                return;
            }

            try
            {
                WebHttpBinding webHttpBinding = new WebHttpBinding();
                ChannelFactory<IFrameDisplayService> clientChannelFactory = new ChannelFactory<IFrameDisplayService>(
                    webHttpBinding, new EndpointAddress(this.GetServiceUrl("FrameDisplayService")));
                clientChannelFactory.Endpoint.Behaviors.Add(new WebHttpBehavior());

                IFrameDisplayService clientChannel = clientChannelFactory.CreateChannel();

                int version = clientChannel.Version();

                MessageBox.Show("Connection succeeded.", "Success");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }

        private void buttonHideFrame_Click(object sender, EventArgs e)
        {
            IFrameDisplayService clientChannel = this.GetFrameDisplayService();
            clientChannel.HideFrame(this.accessCode);
        }

        private void linkLabelAccessCode_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            FrameDisplayClient.UI.Settings.EditAccessCodeForm editAccessCodeForm = new FrameDisplayClient.UI.Settings.EditAccessCodeForm();
            editAccessCodeForm.AccessCode = this.accessCode;
            if (editAccessCodeForm.ShowDialog(this) == DialogResult.OK)
            {
                this.accessCode = editAccessCodeForm.AccessCode;

                // Save the change to settings.
                Settings.Default.AccessCode = this.accessCode;
                Settings.Default.Save();

                this.UpdateServerLabel();
            }
        }

        private void buttonSendMyScreen_Click(object sender, EventArgs e)
        {
            FrameDisplayClient.UI.ScreenSender.ScreenSenderControl screenSenderControl =
                new FrameDisplayClient.UI.ScreenSender.ScreenSenderControl();

            screenSenderControl.Dock = DockStyle.Fill;
            screenSenderControl.SetAccessCode(this.accessCode);
            screenSenderControl.SetFrameDisplayService(this.GetFrameDisplayService());

            this.Controls.Add(screenSenderControl);
            screenSenderControl.BringToFront();
        }
    }


}
